
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h> 


//根据端口号和IP地址  返回一个监听套接字
int create_socket(short port , char * ipstr)
{
    //创建一个套接字
    int sock = socket(AF_INET , SOCK_DGRAM , 0);
    if(sock == -1)
    {
        perror("socket error\n");
        return -1;
    }

    //指定本机的网络地址 ：IP地址和端口号
    struct sockaddr_in Server; 
    Server.sin_family = AF_INET; //指定协议族 
    Server.sin_port = htons(port);//指定端口号 
    Server.sin_addr.s_addr = inet_addr(ipstr);//指定IP地址

    //将本机的网络地址绑定到套接字上面 
    int ret = bind(sock , (struct sockaddr *)&Server , sizeof(Server));
    if(ret == -1)
    {
        perror("bind error\n");
        return -1;
    }
   
    return sock;

}


//./a.out prot ip
int main(int argc , char * argv[])
{
    int sock = create_socket( atoi(argv[1] ),argv[2]);
    if(sock == -1)
    {
        printf("create_socker error\n");
        return -1;
    }


    while(1)
    {
        //保存客户端的网络地址 
        struct sockaddr_in Client;
        socklen_t addrlen = sizeof(Client);

        char recvbuf[1024]={0};

        //接受客户端发送的数据
        int ret = recvfrom(sock ,recvbuf , 1023 , 0 ,  (struct sockaddr *)&Client  , &addrlen );
        if(ret > 0)
        {
                recvbuf[ret]='\0';
                printf("Recv Data : %s from [%s : %d]\n",recvbuf , inet_ntoa( Client.sin_addr ) , ntohs (Client.sin_port)   );
                ret = 0; 
                memset(recvbuf , 0 ,1024);

                int res = sendto(sock , "OK" , 2 , 0 ,  (struct sockaddr *)&Client ,addrlen     ); //回复客户端ok数据
                if(res == -1)
                {
                    perror("sendto error\n");
                }
        }
        sleep(2);


    }
    close(sock);
}




















